<?php

class App_Model_DbTable_Tags extends Ext_Db_Table  
{
    protected $_name = 'tags';
    
    private static $_tagRow = array();
    
    public function getRowById($tagId)
    {
        if(!$tagId)
        {
            return "";
        }
        
        if(isset(self::$_tagRow['id'][$tagId]))
        {
            return self::$_tagRow['id'][$tagId];
        }
        
        $db = $this->getAdapter();
        $safe = $db->quoteInto(" id = ? ", $tagId);
        $row = $this->fetchRow($safe);
        if (!$row) {
            return "";
        }
        $tagRow = $row->toArray();

        self::$_tagRow['id'][$tagId] = $tagRow;
        $tagName = $tagRow['tagName'];
        if($tagName)
        {
            self::$_tagRow['tagName'][$tagName] = $tagRow;
        }
        
        return $tagRow;
    }
    
    public function getRowByName($tagName)
    {
        if(!$tagName)
        {
            return "";
        }
        
        if(isset(self::$_tagRow['tagName'][$tagName]))
        {
            return self::$_tagRow['tagName'][$tagName];
        }
        
        $db = $this->getAdapter();
        $safe = $db->quoteInto(" tagName = ? ", $tagName);
        $row = $this->fetchRow($safe);
        if (!$row) {
            //throw new Exception("Count not find row $id");
            return "";
        }
        $_tagRow = $row->toArray();

        self::$_tagRow['tagName'][$tagName] = $_tagRow;
        $_id = $_tagRow['id'];
        if($_id)
        {
            self::$_tagRow['id'][$_id] = $_tagRow;
        }
        
        return $_tagRow;
    }
        
    public function add($inputArray)
    {
        $tagName = $inputArray['tagName'];
        $_tagRow = $this->getRowByName($tagName);

        if(isset($_tagRow['id']))
        {
            return $_tagRow['id'];
        }
        
        $row = array (
            'tagName'            => $inputArray['tagName'],
            'createTime'         => $inputArray['createTime'],
        );
        try {
            $rows_affected = $this->insert($row);
            $tagId = $this->getAdapter()->lastInsertId();
        }catch (Exception $e){
            trigger_error($e->getMessage(), E_USER_WARNING);
        }
        
        return $tagId;
    }
}  

